package com.qf.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;

/**
 * @author wgy
 * @version v1.0
 * @date 2022/9/1 18:04
 * 创建MyBatis工具类
 */
public class MyBatisUtils {

    //创建SqlSessionFactory
    private static SqlSessionFactory factory;
    //创建ThreadLocal
    private static ThreadLocal<SqlSession> threadLocal=new ThreadLocal<>();
    static {
        //1 读取mybatis配置文件
        try {
            InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
            factory=new SqlSessionFactoryBuilder().build(is);
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //返回SqlSession
    public static SqlSession openSession(){
        SqlSession sqlSession = threadLocal.get();
        if(sqlSession==null){
            sqlSession=factory.openSession();
            threadLocal.set(sqlSession);
        }
        return sqlSession;
    }

    //释放资源
    public static void closeSession(){
        SqlSession sqlSession = openSession();
        if (sqlSession != null) {
            sqlSession.close();
            //解除绑定
            threadLocal.remove();
        }
    }

    //提交事务
    public static void commit(){
        SqlSession sqlSession = openSession();
        if (sqlSession != null) {
            sqlSession.commit();
            closeSession();
        }

    }

    //回滚事务
    public static void rollback(){
        SqlSession sqlSession = openSession();
        if (sqlSession != null) {
            sqlSession.rollback();
            closeSession();
        }
    }

    //返回Mapper对象
    public static <T> T getMapper(Class<T> clazz){
        SqlSession sqlSession = openSession();
        if (sqlSession != null) {
            return sqlSession.getMapper(clazz);
        }
        return null;
    }

}
